package com.yinda.dt.produce.module.main;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.xcgame.oh.DownloadResponseCallback;
import com.yinda.dt.produce.R;
import com.yinda.dt.produce.app.DemoActivity;
import com.yinda.dt.produce.app.DemoConfig;
import com.yinda.dt.produce.app.MyResponseCallback;
import com.yinda.dt.produce.module.login.LoginActivity;
import com.yinda.dt.produce.module.message.MessageActivity;
import com.yinda.dt.produce.module.mine.MineActivity;
import com.yinda.dt.produce.module.order.OrderClassifyActivity;
import com.yinda.dt.produce.module.order.OrderDetailActivity;
import com.yinda.dt.produce.module.order.OtherDetailActivity;
import com.yinda.dt.produce.utils.ApplicationUtil;
import com.yinda.dt.produce.view.HintDialog;
import com.yinda.dt.produce.view.ProgressDialog;
import com.yinda.dt.produce.view.ScrollListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;

public class MainActivity extends DemoActivity implements View.OnClickListener, ViewPager.OnPageChangeListener, SwipeRefreshLayout.OnRefreshListener {

    private CircleImageView civ_userHeadImg;
    private TextView tv_username;
    private TextView tv_message;
    private TextView tv_order;
    private LinearLayout ll_data;
    private FrameLayout fl_notData;
    private TextView tv_noData;
    private LinearLayout ll_waitOrderMore;
    private ScrollListView slv_waitOrder;
    private WaitOrderAdapter orderAdapter;
    private ViewPager vp_recentOrder;
    private RecentOrderAdapter recentOrderAdapter;
    private ImageView iv_month1;
    private ImageView iv_month2;
    private TextView tv_month;
    private SwipeRefreshLayout srl_refresh;
    private RelativeLayout rl_message;
    private RelativeLayout rl_order;

    private LinearLayout ll_function;
    private LinearLayout ll_item1;
    private LinearLayout ll_item2;
    private LinearLayout ll_item3;

    private Call call;

    /**
     * 用于判断是否退出
     */
    private long exitTime = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        srl_refresh = (SwipeRefreshLayout) findViewById(R.id.srl_refresh);
        srl_refresh.setColorSchemeResources(R.color.colorPrimary);
        srl_refresh.setOnRefreshListener(this);

        civ_userHeadImg = (CircleImageView) findViewById(R.id.civ_userHeadImg);
        civ_userHeadImg.setOnClickListener(this);
        Glide.with(this).load(DemoConfig.getInstance(this).getUserimgUrl()).asBitmap().placeholder(R.drawable.default_head).error(R.drawable.default_head).into(civ_userHeadImg);
        tv_username = (TextView) findViewById(R.id.tv_username);
        tv_username.setText(DemoConfig.getInstance(this).getName());
        tv_message = (TextView) findViewById(R.id.tv_message);
        tv_order = (TextView) findViewById(R.id.tv_order);
        ll_data = (LinearLayout) findViewById(R.id.ll_data);
        fl_notData = (FrameLayout) findViewById(R.id.fl_notData);
        tv_noData = (TextView) findViewById(R.id.tv_noData);
        ll_waitOrderMore = (LinearLayout) findViewById(R.id.ll_waitOrderMore);
        ll_waitOrderMore.setOnClickListener(this);
        slv_waitOrder = (ScrollListView) findViewById(R.id.slv_waitOrder);
        orderAdapter = new WaitOrderAdapter();
        slv_waitOrder.setAdapter(orderAdapter);
        vp_recentOrder = (ViewPager) findViewById(R.id.vp_recentOrder);
        vp_recentOrder.addOnPageChangeListener(this);
        recentOrderAdapter = new RecentOrderAdapter();
        vp_recentOrder.setAdapter(recentOrderAdapter);
        tv_month = (TextView) findViewById(R.id.tv_month);
        iv_month1 = (ImageView) findViewById(R.id.iv_month1);
        iv_month2 = (ImageView) findViewById(R.id.iv_month2);
        rl_message = (RelativeLayout) findViewById(R.id.rl_message);
        rl_message.setOnClickListener(this);
        rl_order = (RelativeLayout) findViewById(R.id.rl_order);
        rl_order.setOnClickListener(this);

        ll_function = (LinearLayout) findViewById(R.id.ll_function);
        ll_item1 = (LinearLayout) findViewById(R.id.ll_item1);
        ll_item1.setOnClickListener(this);
        ll_item2 = (LinearLayout) findViewById(R.id.ll_item2);
        ll_item2.setOnClickListener(this);
        ll_item3 = (LinearLayout) findViewById(R.id.ll_item3);
        ll_item3.setOnClickListener(this);

        String isPm = DemoConfig.getInstance(this).getIsPm();
        if (!isPm.equals("") && isPm.equals("1")) {
            ll_function.setVisibility(View.VISIBLE);
        } else {
            ll_function.setVisibility(View.GONE);
        }

        checkVersion();
        toBindPushUser();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (call != null) {
            call.cancel();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (DemoConfig.getInstance(this).getUserimgUpdate()) {
            DemoConfig.getInstance(this).setUserimgUpdate(false);
            Glide.with(this).load(DemoConfig.getInstance(this).getUserimgUrl()).asBitmap().placeholder(R.drawable.default_head).error(R.drawable.default_head).into(civ_userHeadImg);
        }
        srl_refresh.setRefreshing(true);
        getMainData();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.rl_message) {
            Intent intent = new Intent(this, MessageActivity.class);
            startActivity(intent);
        }
        if (id == R.id.rl_order) {
            Intent intent = new Intent(this, OrderClassifyActivity.class);
            intent.putExtra("isWait", false);
            startActivity(intent);
        }
        if (id == R.id.ll_waitOrderMore) {
            Intent intent = new Intent(this, OrderClassifyActivity.class);
            intent.putExtra("isWait", true);
            startActivity(intent);
        }
        if (id == R.id.civ_userHeadImg) {
            Intent intent = new Intent(this, MineActivity.class);
            startActivity(intent);
        }
        if (id == R.id.ll_item1) {
            Intent intent = new Intent(this, OtherDetailActivity.class);
            intent.putExtra("type", 1);
            startActivity(intent);
        }
        if (id == R.id.ll_item2) {
            Intent intent = new Intent(this, OtherDetailActivity.class);
            intent.putExtra("type", 2);
            startActivity(intent);
        }
        if (id == R.id.ll_item3) {
            Intent intent = new Intent(this, OtherDetailActivity.class);
            intent.putExtra("type", 3);
            startActivity(intent);
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        if (position == 0) {
            tv_month.setText("本月");
            iv_month1.setImageResource(R.drawable.main_tab_select);
            iv_month2.setImageResource(R.drawable.main_tab_noselect);
        }
        if (position == 1) {
            tv_month.setText("上月");
            iv_month1.setImageResource(R.drawable.main_tab_noselect);
            iv_month2.setImageResource(R.drawable.main_tab_select);
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onRefresh() {
        getMainData();
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                showToast("再按一次返回键退出");
                exitTime = System.currentTimeMillis();
            } else {
                //退出代码
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void getMainData() {
        try {
            String url = getString(R.string.defaultURL) + "/phone1_0!homepage.action";
            JSONObject jsonParams = new JSONObject();
            jsonParams.put("uid", DemoConfig.getInstance(this).getUid());
            call = post(url, jsonParams, new MyResponseCallback() {

                @Override
                public void onFinish() {
                    super.onFinish();
                    if (srl_refresh.isRefreshing()) {
                        srl_refresh.setRefreshing(false);
                    }
                }

                @Override
                public void onSuccess(JSONObject jsonResult) {
                    super.onSuccess(jsonResult);

                    try {
                        JSONObject jsonHead = jsonResult.getJSONObject("head");
                        int status = jsonHead.getInt("status");
                        String info = jsonHead.getString("info");
                        if (status == 1) {

                            fl_notData.setVisibility(View.GONE);
                            ll_data.setVisibility(View.VISIBLE);

                            JSONObject jsonData = jsonResult.getJSONObject("data");
                            tv_message.setText(jsonData.getString("message"));
                            tv_order.setText(jsonData.getString("order"));
                            JSONArray jsonOrderList = jsonData.getJSONArray("orderList");
                            if (jsonOrderList.length() == 0) {
                                tv_noData.setVisibility(View.VISIBLE);
                            } else {
                                tv_noData.setVisibility(View.GONE);
                            }
                            orderAdapter.setJsonOrderList(jsonOrderList);
                            slv_waitOrder.notifyDataSetChanged();
                            JSONArray jsonReview = jsonData.getJSONArray("mothReview");
                            recentOrderAdapter.monthFragment.setJsonReviews(jsonReview);
                            JSONArray jsonBeforeReview = jsonData.getJSONArray("BeforeMothReview");
                            recentOrderAdapter.beforeMonthFragment.setJsonReviews(jsonBeforeReview);
                        } else {
                            if (info.contains("key无效") || info.toLowerCase().contains("loginout") || info.contains("未登录")) {
                                DemoConfig.getInstance(getContext()).setKey("");
                                DemoConfig.getInstance(getContext()).setIsLogin(false);
                                showToast("请重新登录");
                                Intent intent = new Intent(getContext(), LoginActivity.class);
                                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivity(intent);
                            } else {
                                showToast(info);
                            }
                        }


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    private class WaitOrderAdapter extends ScrollListView.Adapter {

        private JSONArray jsonOrderList;

        public void setJsonOrderList(JSONArray jsonOrderList) {
            this.jsonOrderList = jsonOrderList;
        }

        @Override
        public View getItemView(ViewGroup parent, int position) {
            View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.adapter_order_wait, parent, false);
            LinearLayout ll_item = (LinearLayout) view.findViewById(R.id.ll_item);
            TextView tv_orderTitle = (TextView) view.findViewById(R.id.tv_orderTitle);
            TextView tv_orderTime = (TextView) view.findViewById(R.id.tv_orderTime);
            TextView tv_orderUser = (TextView) view.findViewById(R.id.tv_orderUser);
            TextView tv_orderNumber = (TextView) view.findViewById(R.id.tv_orderNumber);
            ImageView iv_refuse = (ImageView) view.findViewById(R.id.iv_refuse);
            try {
                final JSONObject jsonOrder = jsonOrderList.getJSONObject(position);
                String title;
                switch (jsonOrder.getString("approvalCode")) {
                    case "1":
                        title = "订单申请";
                        break;
                    case "2":
                        title = "订单审批";
                        break;
                    case "3":
                        title = "计划安排";
                        break;
                    case "4":
                        title = "技术资料";
                        break;
                    case "5":
                        title = "半成品";
                        break;
                    case "6":
                        title = "黑件出厂";
                        break;
                    case "7":
                        title = "镀锌申请";
                        break;
                    case "8":
                        title = "镀锌申请-副总审批";
                        break;
                    case "9":
                        title = "白件质检";
                        break;
                    case "10":
                        title = "计划发货";
                        break;
                    case "11":
                        title = "项目收货";
                        break;
                    case "12":
                        title = "新建项目施工";
                        break;
                    case "13":
                        title = "施工质检";
                        break;
                    case "14":
                        title = "计划安排副总审核";
                        break;
                    case "15":
                        title = "改造项目施工";
                        break;
                    case "16":
                        title = "零星项目施工";
                        break;
                    case "18":
                        title = "外协审批";
                        break;
                    default:
                        title = "未知";
                        break;
                }
                tv_orderTitle.setText(title);
                tv_orderUser.setText(jsonOrder.getJSONObject("user").getString("userName"));
                tv_orderNumber.setText(jsonOrder.getString("orderId"));
                tv_orderTime.setText(jsonOrder.getString("orderTime"));
                if (jsonOrder.getString("reviewStatus").equals("0")) {
                    iv_refuse.setVisibility(View.INVISIBLE);
                } else {
                    iv_refuse.setVisibility(View.VISIBLE);
                }

                ll_item.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        Log.d("xiaocan", jsonOrder.toString());

                        try {
                            Intent intent = new Intent(MainActivity.this, OrderDetailActivity.class);
                            intent.putExtra("orderId", jsonOrder.getString("Id"));
                            intent.putExtra("approvalCode", jsonOrder.getString("approvalCode"));
                            intent.putExtra("orderType", jsonOrder.getString("orderType"));
                            intent.putExtra("orderStatus", jsonOrder.getString("orderstatus"));
                            startActivity(intent);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                });

            } catch (JSONException e) {
                e.printStackTrace();
            }
            return view;
        }


        @Override
        public int getItemCount() {
            if (jsonOrderList == null) {
                return 0;
            }
            return jsonOrderList.length();
        }
    }

    private class RecentOrderAdapter extends FragmentStatePagerAdapter {

        MonthFragment monthFragment;
        BeforeMonthFragment beforeMonthFragment;

        public RecentOrderAdapter() {
            super(getSupportFragmentManager());
            monthFragment = new MonthFragment();
            beforeMonthFragment = new BeforeMonthFragment();
        }

        @Override
        public Fragment getItem(int position) {
            if (position == 0) {
                return monthFragment;
            }
            if (position == 1) {
                return beforeMonthFragment;
            }
            return null;
        }

        @Override
        public int getCount() {
            return 2;
        }
    }


    public void toBindPushUser() {
        if (isFinishing()) {
            return;
        }
        String url = getString(R.string.defaultURL) + "/phone1_0!registerDeviceToken.action";
        try {
            if (!DemoConfig.getInstance(this).getToken().equals("")) {
                JSONObject jsonParams = new JSONObject();
                jsonParams.put("registrationID", DemoConfig.getInstance(this).getToken());
                post(url, jsonParams, new MyResponseCallback() {

                });
            } else {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        toBindPushUser();
                    }
                }, 30 * 1000);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    /**
     * 检查版本
     */
    public void checkVersion() {

        String url = getString(R.string.defaultURL) + "/phone1_0!checkUpdate.action";
        JSONObject jsonParams = new JSONObject();
        post(url, jsonParams, new MyResponseCallback() {

            @Override
            public void onSuccess(JSONObject jsonResult) {
                super.onSuccess(jsonResult);

                try {

                    JSONObject jsonHead = jsonResult.getJSONObject("head");
                    int status = jsonHead.getInt("status");
                    if (status == 1) {
                        JSONObject jsonData = jsonResult.getJSONObject("data");
                        String updateContent = jsonData.getString("updateContent");
                        int updateVersionCode = jsonData.getInt("updateVersionCode");
                        String updateVersionName = jsonData.getString("updateVersionName");
                        String updateUrl = jsonData.getString("updateUrl");
                        boolean forced;
                        if (jsonData.getString("forced").equals("0")) {
                            forced = false;
                        } else {
                            forced = true;
                        }

                        DemoConfig.getInstance(getContext()).setNewVersionCode(updateVersionCode);
                        DemoConfig.getInstance(getContext()).setNewVersionName(updateVersionName);
                        DemoConfig.getInstance(getContext()).setUpdateAppUrl(updateUrl);

                        checkAppUpdate(updateContent, updateVersionCode, updateVersionName, updateUrl, forced);

                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });

    }

    private void checkAppUpdate(String updateContent, int updateVersionCode, String updateVersionName, final String updateUrl, boolean isForced) {
        if (ApplicationUtil.isNeedUpdate(this, updateVersionCode)) {
            if (isForced) {
                HintDialog hintDialog = new HintDialog(this);
                hintDialog.setTitle("温馨提示");
                hintDialog.setContent(updateContent);
                hintDialog.setCanceledOnTouchOutside(false);
                hintDialog.setCancelable(false);
                hintDialog.setConfirmButtonText("立即更新");
                hintDialog.setCancelButtonText("稍后更新");
                hintDialog.setOnClickListener(new HintDialog.OnClickListener() {
                    @Override
                    public void onConfirm(Dialog dialog) {
                        dialog.dismiss();
                        network_downloadApp(updateUrl, true);
                    }

                    @Override
                    public void onCancel(Dialog dialog) {
                        dialog.dismiss();
                        finish();
                    }
                });
                hintDialog.show();
            } else {
                HintDialog hintDialog = new HintDialog(this);
                hintDialog.setTitle("温馨提示");
                hintDialog.setContent(updateContent);
                hintDialog.setCanceledOnTouchOutside(false);
                hintDialog.setCancelable(false);
                hintDialog.setConfirmButtonText("立即更新");
                hintDialog.setCancelButtonText("稍后更新");
                hintDialog.setOnClickListener(new HintDialog.OnClickListener() {
                    @Override
                    public void onConfirm(Dialog dialog) {
                        dialog.dismiss();
                        network_downloadApp(updateUrl, false);
                    }

                    @Override
                    public void onCancel(Dialog dialog) {
                        dialog.dismiss();
                    }
                });
                hintDialog.show();
            }
        }
    }

    private void network_downloadApp(String url, final boolean isForced) {

        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setCancelable(false);
        progressDialog.setProgress(0);
        myOkHttp.downloadFile(this, url, new DownloadResponseCallback() {

            @Override
            public void onStart() {
                super.onStart();
                progressDialog.show();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                progressDialog.dismiss();
            }

            @Override
            public void onProgress(int progress) {
                super.onProgress(progress);
                progressDialog.setProgress(progress);
            }

            @Override
            public void onSuccess(String filePath) {
                super.onSuccess(filePath);

                ApplicationUtil.installApk(getContext(), filePath);
            }

        });
    }

}
